$(document).ready(function() {
	window. canvas = document.getElementById("myCanvas");
	window. ctx = canvas.getContext("2d");
	var drawing = false;
	var x = 0;
	var y = 0;
	ctx.lineJoin = "round";
	ctx.lineWidth = 5;
	ctx.lineCap = "round";
	var stroke = [];
	canvas.addEventListener("mousedown", function(e) {
		drawing = true;
		x = e.pageX - canvas.offsetLeft;
		y = e.pageY - canvas.offsetTop;
		ctx.strokeStyle=$("#color").val();
		ctx.lineWidth=$("#lineWidth").val();
			stroke = [];
		var point = {
			x : x,
			y : y
		};
		stroke.push(point);
	}, false);

	canvas.addEventListener("mousemove", function(e) {
		if (drawing) {
			ctx.beginPath()
			ctx.moveTo(x, y);
			x = e.pageX - canvas.offsetLeft;
			y = e.pageY - canvas.offsetTop;
			ctx.lineTo(x, y);
			var point = {
				x : x,
				y : y
			};
			stroke.push(point);
			ctx.stroke();

		}
	}, false);
	canvas.addEventListener("mouseup", function(e) {
		drawing = false;

		var mys = stroke;

		stroke = [];
		mys={c:$("#color").val(),lw:$("#lineWidth").val(),s:mys};

		$.ajax({
			type : "POST",
			url : "stroke",
			data : JSON.stringify(mys),
			success : function(a) {
				console.log(a);
			},
			
			contentType : "text/json"
		}).fail(function(e) {
			console.error(e);
		});
	}, false);

	var newStrokes = function() {

		$.ajax({
			type : "GET",
			url : "newStrokes",
			success : function(strokes) {
				
				for (sn in strokes) {
					stroke = strokes[sn];
					ctx.beginPath();
					var point = stroke.s.shift();
					ctx.moveTo(point.x, point.y);
					for (pn in stroke.s) {
						point = stroke.s[pn];

						ctx.lineTo(point.x, point.y);
					}
					ctx.lineWidth=stroke.lw;
					ctx.strokeStyle=stroke.c;
					ctx.stroke();
					ctx.strokeStyle=$("#color").val();
					ctx.lineWidth=$("#lineWidth").val();
				}
				setTimeout(newStrokes, 1000);
			},
			dataType : "json"
		}).fail(function(e) {
			console.error(e);
			setTimeout(newStrokes, 1000);
		});

	};
	var download=$("#download");
	download.click(function(){
		download.attr("href",canvas.toDataURL("image/png"));
	});
	setTimeout(newStrokes, 1000);
});